import React, { useState } from 'react';
import {
  Space,
  Tag,
  Popconfirm,
  message,
  Tooltip,
  Typography,
  Modal,
  Drawer,
  Avatar,
  List,
  Button,
  Row,
  Col,
  Card,
  Table,
  Input,
  Tree,
  Spin,
  Badge,
  Descriptions,
} from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  TeamOutlined,
  EyeOutlined,
  UserOutlined,
  ApartmentOutlined,
  PlusOutlined,
  ReloadOutlined,
  FolderOutlined,
  FolderOpenOutlined,
} from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import { useTeams, useTeamActions, useTeamMembers } from '../../hooks/business/useTeams';
import { useDepartmentTree } from '../../hooks/business/useDepartments';
import { Team, TeamMember, Department } from '@/types/rbac';
import { getDepartmentInfo, filterData } from '@/utils/business';
import TeamForm from '../../components/TeamForm';

const { Text, Title } = Typography;
const { Search } = Input;

const Teams: React.FC = () => {
  const [searchKeyword, setSearchKeyword] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [formVisible, setFormVisible] = useState(false);
  const [editingTeam, setEditingTeam] = useState<Team | undefined>();
  const [viewingTeam, setViewingTeam] = useState<Team | undefined>();
  const [detailsVisible, setDetailsVisible] = useState(false);
  const [selectedDepartmentId, setSelectedDepartmentId] = useState<string | null>(null);

  // 使用hooks
  const { teams, loading, refresh } = useTeams({
    page: currentPage,
    size: pageSize,
    keyword: searchKeyword,
    departmentId: selectedDepartmentId, // 添加部门筛选参数
  });

  const { departmentTree, loading: departmentLoading, refresh: refreshDepartments } = useDepartmentTree();

  const { loading: actionLoading, createTeam, updateTeam, deleteTeam, deleteTeams } = useTeamActions();

  const { members, loading: membersLoading } = useTeamMembers(
    viewingTeam?.id,
    { page: 1, size: 50 }
  );

  // 过滤团队数据
  const filteredTeams = filterData(teams, searchKeyword, ['name', 'code', 'description']);

  // 构建部门树数据
  const buildTreeData = (departments: Department[]): any[] => {
    return departments.map(dept => ({
      title: dept.name,
      key: dept.id,
      icon: <ApartmentOutlined />,
      children: dept.children ? buildTreeData(dept.children) : undefined,
    }));
  };

  const treeData = [
    {
      title: '全部部门',
      key: 'all',
      icon: <FolderOutlined />,
      children: buildTreeData(departmentTree),
    }
  ];

  // 处理部门树选择
  const handleDepartmentSelect = (selectedKeys: React.Key[]) => {
    const selectedKey = selectedKeys[0] as string;
    if (selectedKey === 'all') {
      setSelectedDepartmentId(null);
    } else {
      setSelectedDepartmentId(selectedKey);
    }
    setCurrentPage(1); // 重置到第一页
  };

  const handleCreateTeam = () => {
    setEditingTeam(undefined);
    setFormVisible(true);
  };

  const handleEditTeam = (team: Team) => {
    setEditingTeam(team);
    setFormVisible(true);
  };

  const handleViewTeam = (team: Team) => {
    setViewingTeam(team);
    setDetailsVisible(true);
  };

  const handleFormSubmit = async (values: any) => {
    try {
      if (editingTeam) {
        await updateTeam(editingTeam.id, values);
      } else {
        await createTeam(values);
      }
      setFormVisible(false);
      setEditingTeam(undefined);
      refresh();
    } catch (error) {
      console.error('操作失败:', error);
    }
  };

  const handleDeleteTeam = async (id: string) => {
    try {
      await deleteTeam(id);
      refresh();
    } catch (error) {
      console.error('删除失败:', error);
    }
  };

  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的团队');
      return;
    }

    Modal.confirm({
      title: '批量删除确认',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个团队吗？`,
      onOk: async () => {
        try {
          await deleteTeams(selectedRowKeys);
          setSelectedRowKeys([]);
          refresh();
        } catch (error) {
          console.error('批量删除失败:', error);
        }
      },
    });
  };

  const handleSearch = (value: string) => {
    setSearchKeyword(value);
  };

  const columns: ColumnsType<Team> = [
    {
      title: '团队名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render: (name: string, record: Team) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{name}</div>
          <div style={{ fontSize: '12px', color: '#64748b' }}>
            代码: {record.code}
          </div>
        </div>
      ),
    },
    {
      title: '所属部门',
      dataIndex: 'departmentId',
      key: 'department',
      width: 150,
      render: (deptId: string) => {
        if (!deptId) return <Text type="secondary">未分配</Text>;
        const dept = getDepartmentInfo(deptId, departmentTree);
        return dept ? (
          <Tag color="blue" icon={<ApartmentOutlined />}>
            {dept.name}
          </Tag>
        ) : <Text type="secondary">部门不存在</Text>;
      },
    },
    {
      title: '成员数量',
      dataIndex: 'memberCount',
      key: 'memberCount',
      width: 120,
      align: 'center',
      render: (count: number) => (
        <Tag color="geekblue" icon={<UserOutlined />}>
          {count || 0}人
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      align: 'center',
      render: (status: string | number = 'active') => {
        // 处理后端返回的数字状态：1为启用，0为禁用
        const isActive = status === 'active' || status === 1;
        return (
          <Tag color={isActive ? 'green' : 'red'}>
            {isActive ? '启用' : '禁用'}
          </Tag>
        );
      },
    },
    {
      title: '操作',
      key: 'actions',
      width: 100,
      fixed: 'right',
      render: (_, record: Team) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="text"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleViewTeam(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEditTeam(record)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个团队吗？"
            onConfirm={() => handleDeleteTeam(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="text"
                size="small"
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 表格行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: React.Key[]) => {
      setSelectedRowKeys(keys as string[]);
    },
  };

  return (
    <div>
      {/* 页面标题 */}
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <Title level={4} style={{ margin: 0, display: 'flex', alignItems: 'center' }}>
            <TeamOutlined style={{ marginRight: 8, color: '#1890ff' }} />
            团队管理
            {selectedDepartmentId && (
              <span style={{ fontSize: 14, fontWeight: 'normal', color: '#666', marginLeft: 8 }}>
                - {(() => {
                  const findDeptName = (depts: Department[], id: string): string => {
                    for (const dept of depts) {
                      if (dept.id === id) return dept.name;
                      if (dept.children) {
                        const found = findDeptName(dept.children, id);
                        if (found) return found;
                      }
                    }
                    return '';
                  };
                  return findDeptName(departmentTree, selectedDepartmentId);
                })()}
              </span>
            )}
          </Title>
          <Text type="secondary">管理团队信息和成员分配</Text>
        </div>
        <Space>
          <Search
            placeholder="搜索团队名称、代码或描述"
            allowClear
            style={{ width: 300 }}
            onSearch={handleSearch}
          />
          <Button 
            icon={<ReloadOutlined />} 
            onClick={refresh}
            loading={loading}
            style={{
              borderColor: '#d9d9d9',
              color: '#666'
            }}
          >
            刷新
          </Button>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={handleCreateTeam}
            style={{ borderRadius: 6 }}
          >
            新建团队
          </Button>
          {selectedRowKeys.length > 0 && (
            <Button
              danger
              icon={<DeleteOutlined />}
              onClick={handleBatchDelete}
            >
              批量删除({selectedRowKeys.length})
            </Button>
          )}
        </Space>
      </div>

      <Row gutter={16}>
        {/* 左侧部门树 */}
        <Col span={7}>
          <Card
            title={
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>部门结构</span>
                <Space>
                  <Button
                    type="text"
                    icon={<ReloadOutlined />}
                    onClick={refreshDepartments}
                    size="small"
                  />
                </Space>
              </div>
            }
            style={{ height: 'calc(100vh - 300px)' }}
            bodyStyle={{ height: 'calc(100vh - 350px)', overflow: 'auto', padding: '16px' }}
          >
            {departmentLoading ? (
              <div style={{ textAlign: 'center', padding: '20px' }}>
                加载中...
              </div>
            ) : (
              <Tree
                showLine
                showIcon
                defaultExpandAll
                selectedKeys={selectedDepartmentId ? [selectedDepartmentId] : ['all']}
                treeData={treeData}
                onSelect={handleDepartmentSelect}
                style={{ 
                  fontSize: '15px',
                  height: '100%',
                  overflow: 'auto'
                }}
                height={window.innerHeight - 400}
                virtual
              />
            )}
          </Card>
        </Col>

        {/* 右侧团队管理内容 */}
        <Col span={17}>
          <Card bodyStyle={{ padding: 2 }}>
            <div style={{ padding: '0 24px 24px 24px' }}>
              <Table
                columns={columns}
                dataSource={filteredTeams}
                loading={loading}
                rowKey="id"
                rowSelection={rowSelection}
                pagination={{
                  current: currentPage,
                  pageSize: pageSize,
                  total: filteredTeams.length,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  showTotal: (total, range) =>
                    `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`,
                  onChange: (page, size) => {
                    setCurrentPage(page);
                    setPageSize(size || 10);
                  },
                }}
                scroll={{ x: 1200, y: 'calc(100vh - 400px)' }}
                size="middle"
              />
            </div>
          </Card>
        </Col>
      </Row>
        {/* 团队表单Modal */}
        <TeamForm
          visible={formVisible}
          team={editingTeam}
          loading={actionLoading}
          onSubmit={handleFormSubmit}
          onCancel={() => {
            setFormVisible(false);
            setEditingTeam(undefined);
          }}
        />

      {/* 团队详情侧边栏 */}
      <Drawer
        title="团队详情"
        placement="right"
        width={600}
        open={detailsVisible}
        onClose={() => setDetailsVisible(false)}
        extra={
          <Space>
            <Button 
              type="primary" 
              icon={<EditOutlined />}
              onClick={() => {
                setDetailsVisible(false);
                if (viewingTeam) {
                  handleEditTeam(viewingTeam);
                }
              }}
            >
              编辑
            </Button>
          </Space>
        }
      >
        {viewingTeam && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="团队名称">
              <Space>
                <TeamOutlined style={{ color: '#1890ff' }} />
                <Text strong>{viewingTeam.name}</Text>
              </Space>
            </Descriptions.Item>
            
            <Descriptions.Item label="团队代码">
              <Text code>{viewingTeam.code}</Text>
            </Descriptions.Item>
            
            <Descriptions.Item label="状态">
              <Badge 
                status={viewingTeam.status === 'active' || viewingTeam.status === 1 ? 'success' : 'error'} 
                text={viewingTeam.status === 'active' || viewingTeam.status === 1 ? '启用' : '禁用'} 
              />
            </Descriptions.Item>
            
            <Descriptions.Item label="成员数量">
              <Text>{viewingTeam.memberCount}人</Text>
            </Descriptions.Item>
            
            <Descriptions.Item label="所属部门">
              {viewingTeam.departmentId ? (
                (() => {
                  const dept = getDepartmentInfo(viewingTeam.departmentId!, departmentTree);
                  return dept ? (
                    <Tag color="blue">{dept.name}</Tag>
                  ) : <Text type="secondary">部门不存在</Text>;
                })()
              ) : (
                <Text type="secondary">未分配</Text>
              )}
            </Descriptions.Item>
            
            <Descriptions.Item label="描述">
              <Text>{viewingTeam.description || '暂无描述'}</Text>
            </Descriptions.Item>
            
            <Descriptions.Item label="创建时间">
              <Text>{viewingTeam.createTime ? new Date(viewingTeam.createTime).toLocaleString() : '-'}</Text>
            </Descriptions.Item>
          </Descriptions>
        )}
        
        {/* 团队成员列表 */}
        {members.length > 0 && (
          <div style={{ marginTop: 24 }}>
            <Text strong style={{ fontSize: 16, marginBottom: 16, display: 'block' }}>团队成员</Text>
            <div style={{ marginTop: 12 }}>
              {members.map((member: TeamMember) => (
                <div key={member.id} style={{ 
                  padding: '12px 16px',
                  border: '1px solid #f0f0f0',
                  borderRadius: 6,
                  marginBottom: 8,
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  backgroundColor: '#fafafa'
                }}>
                  <div>
                    <Text strong>{member.realName || member.username}</Text>
                    <Text type="secondary" style={{ marginLeft: 8, fontSize: 12 }}>
                      {member.email}
                    </Text>
                  </div>
                  <Space>
                    {member.isLeader && <Tag color="blue">组长</Tag>}
                    {member.position && <Tag color="geekblue">{member.position}</Tag>}
                  </Space>
                </div>
              ))}
            </div>
          </div>
        )}
      </Drawer>
    </div>
  );
};

export default Teams;